package a10threadsafe2;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2024-04-17
 * Time: 11:26
 */
public class MyRunnanble implements Runnable{
    int ticket = 0;   //不用加static
    @Override
    public void run() {
        //1. 循环
        //2. 同步代码块(同步方法)
        //3. 判断共享数据是否到末尾
        //4. 判断共享数据是否到了末尾,如果没有到末尾

        //1. 循环
        while(true) {
            //2. 同步代码块(同步方法)
            synchronized (MyRunnanble.class) {
                //3. 判断共享数据是否到末尾
                if (extracted()) break;
            }
        }

    }

    private boolean extracted() {
        if (ticket == 100){
            return true;
        }else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //4. 判断共享数据是否到了末尾,如果没有到末尾
            ticket++;
            System.out.println(Thread.currentThread().getName()+"在卖第"+ticket+"张票!!!");
        }
        return false;
    }
}
